require('../css/commCss/normalize.css')
require('../css/commCss/reset.css')
require('../css/commCss/property.css')
require('../lib/flexible')
require('../font/iconfont.css')
require('../css/amend.less')
    //引入axios
const axios = require('axios')
    //导入weui
require("weui")
const weui = require("weui.js")

document.addEventListener('DOMContentLoaded', function() {

    let imgurl = document.querySelector('#imgurl')
    let nickname = document.querySelector('#nickname')
    const sex = document.querySelector('#sex')
    const birthday = document.querySelector('#birthday')
    const province = document.querySelector('#province')
    const city = document.querySelector('#city')
    const sign = document.querySelector('#sign')
    const currentCount = document.querySelector('#currentCount')

    sign.addEventListener('input', function() {
        currentCount.textContent = sign.value.length
    })


    //渲染个人信息数据
    axios.get('http://139.9.177.51:8099/users/accountinfo', {
        params: {
            userId: localStorage.userId
        }
    }).then(function(res) {
        let data = res.data.data

        nickname.value = data.nickname

        if (data.imgurl) {
            imgurl.src = data.imgurl
        }
        if (data.gender) {
            sex.textContent = data.gender
        }
        if (data.birthday) {
            //截取字符串substr,slice都可以
            // birthday.textContent = data.birthday.substr(0, 10)
            birthday.textContent = data.birthday.slice(0, 10)
        }
        if (data.address) {
            province.textContent = data.address.split(',')[0]
            city.textContent = data.address.split(',')[1]
        }
        if (data.sign) {
            sign.value = data.sign
            currentCount.textContent = sign.value.length
        }

        // console.log(data.src);
    })



    document.querySelector('#goBack').addEventListener('click', function() {
        //返回上一个页面
        history.go(-1)
    })

    //选择性别
    document.querySelector('#sexPicker').addEventListener('click', function() {
        weui.picker([{
            label: '男',
            value: 0
        }, {
            label: '女',
            value: 1
        }], {
            onConfirm: function(result) {
                // console.log(result);
                document.querySelector('#sex').textContent =
                    result[0].label
            },
            title: '请选择性别'
        });
    });


    function fillZero(n) {
        return n < 10 ? n + '0' : n
    }
    //选择生日
    document.querySelector('#birthdayPicker').addEventListener('click', function() {
        weui.datePicker({
            start: new Date().getFullYear() - 80,
            end: new Date().getFullYear(),
            onConfirm: function(result) {
                // console.log(result);
                let str = [result[0].value, fillZero(result[1].value), fillZero(result[2].value)].join('-')
                    // console.log(str);
                document.querySelector('#birthday').textContent = str;
            },
            title: '请选择生日'
        });
    })

    let provinceArr = [] //所有省份
    let cityArr = [] //省份下面的城市

    axios.get('http://139.9.177.51:8099/address/province')
        .then(function(res) {
            // console.log(res.data);
            //{addressId: 110000, name: "北京市", pid: 0}
            provinceArr = res.data.data.map(function(item) {
                    return { label:  item.name, value: item.addressId }
                })
                //返回的provinceArr是一个数组
                // console.log(provinceArr);

        })



    //选择省份
    document.querySelector('#provincePicker').addEventListener('click', function() {
        weui.picker(provinceArr, {
            onConfirm: function(result) {
                // console.log(result);
                document.querySelector('#province').textContent =
                    result[0].label

                //声明pid参数值
                let pid = result[0].value
                axios.get('http://139.9.177.51:8099/address/city/' + pid)
                    .then(function(res) {
                        // console.log(res.data);
                        //{addressId: 110000, name: "北京市", pid: 0}
                        let data = res.data.data
                            //cityArr城市对象的值
                        cityArr = data.map(function(item) {
                                return { label:  item.name, value: item.addressId }
                            })
                            //修改后的cityArr数组在点击省份axios发送成功里面
                            //所以要用修改后的cityArr数组只能在这里面用
                        document.querySelector('#city').textContent = cityArr[0].label

                    })

            },
            title: '请选择省份'
        });
    });

    //选择城市
    document.querySelector('#cityPicker').addEventListener('click', function() {
        if (cityArr = []) {
            weui.alert('请先选择城市')
        }
        weui.picker(cityArr, {
            onConfirm: function(result) {
                // console.log(result);
                document.querySelector('#city').textContent =
                    result[0].label
            },
            title: '请选择城市'
        });
    });

    /*
  头像上传:
    1.获取是input[type="file"]的files 
    2.参数需要使用FormData对象  let fd=new FormData()  fd.append("xxx",file)
    3.上传的参数是fd对象
  */
    document.querySelector('#fileImg').addEventListener('change', function() {
        //  写files是因为用户可能选择多张图片
        //this代表当前input type="file"输入框
        //this.files里面是FileList数组
        //this.files[0]代表第一个选择文件的信息File
        console.log(this.files[0]);
        let file = this.files[0]
            //图片上传必须借助FormData
            //FormData是js的一个内置对象
            //内置对象例如：Math.ceil(3.1)能直接用
            //实例化一个fd对象，fd是FormData缩写
        let fd = new FormData()
            //设置fd的键imgurl,值file第一个选择文件的信息
        fd.append('imgurl', file)
            // (,fd)直接写fd,因为fd是对象,不用再加{}
        axios.post("http://139.9.177.51:8099/users/upload", fd)
            .then(function(res) {
                if (res.data.status === 1) { //失败
                    weui.toast(res.data.msg)
                } else {
                    weui.toast('修改成功')
                        //拼接最新上传图片的路径,显示到页面中
                    document.querySelector('#imgurl').src =
                        'http://139.9.177.51:8099' + res.data.data
                }
            })
    })



    //#region
    // 默写传图片http://139.9.177.51:8099/users/upload
    // document.querySelector('#fileImg').addEventListener('change', function() {
    //     let file = this.files[0]

    //     let fd = new FormData()
    //     fd.append('imgurl', file)

    //     axios.post('http://139.9.177.51:8099/users/upload', fd)
    //         .then(function(res) {
    //             if (res.data.status === 0) {
    //                 weui.toast('修改成功')
    //                     //修改图片路径要在跳转前
    //                 imgurl.src = 'http://139.9.177.51:8099' + res.data.data
    //                     // console.log(res);
    //             } else {
    //                 weui.alert(res.data.msg)
    //             }
    //         })
    // })
    //#endregion

    document.querySelector('#imgurl').addEventListener('click', function() {
        document.querySelector('#fileImg').click()
    })

    //保存修改信息
    const saveBtn = document.querySelector('#saveBtn')

    saveBtn.addEventListener('click', function() {

        let params = {
            imgurl: document.querySelector('#imgurl').src,
            nickname: document.querySelector('#nickname').value,
            gender: document.querySelector("#sex").textContent,
            birthday: document.querySelector("#birthday").textContent,
            address: [document.querySelector("#province").textContent, document.querySelector("#city").textContent],
            sign: document.querySelector("#sign").value,
            userId: localStorage.userId
        }
        console.log(params);

        axios.post('http://139.9.177.51:8099/users/userEdit', params)
            .then(function(res) {
                if (res.data.status === 0) {
                    weui.toast('修改成功', {
                        callback: function() {
                            location.href = './mine.html'
                        }
                    })
                } else {
                    weui.alert('修改失败')
                }

            })

    })
})